package com.mansoor.app.islamicnames.activities;

import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.*;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import com.mansoor.app.islamicnames.adapters.NameListAdapter;
import com.mansoor.app.islamicnames.beans.Name;
import com.mansoor.app.islamicnames.db.NamesDao;
import com.mansoor.app.islamicnames.services.RestClient;
import com.mansoor.app.islamicnames.services.RestClientImpl;
import org.json.JSONException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.mansoor.app.islamicnames.util.AppConstant.*;

/**
 * Created by IntelliJ IDEA.
 * User: TKMAQ61
 * Date: Oct 14, 2009
 * Time: 11:30:18 AM
 */
public class NameList extends ListActivity
{

    private RestClient client = new RestClientImpl();
    private List<Name> names = null;
    private Integer page_count = 0;
    private String gender;
    private String alphabet;
    private Boolean first_run = false;
    private ImageButton preImage;
    private ImageButton nextImage;
    private Integer current_page = 0;
    private ServiceThread serviceThread = new ServiceThread();
    private View menu;
    private ProgressDialog dialog;
    private TextView statusBox;
    // private PaginationThread pThread = new PaginationThread();

    private NameListAdapter nameListAdapter;
    private final Handler handler = new Handler()
    {
        public void handleMessage(final Message msg)
        {

            dismissDialog(PROGRESS);
            if (names == null)
            {
                names = new ArrayList<Name>();
            }

            nameListAdapter = new NameListAdapter(getApplicationContext(), R.layout.namelist_row, names);
            setListAdapter(nameListAdapter);
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        Boolean next = true;
        Boolean pre = true;

        super.onCreate(savedInstanceState);
        setContentView(R.layout.list);
        final ListView listView = getListView();

        listView.setItemsCanFocus(false);
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        listView.setOnCreateContextMenuListener(this);

        first_run = (Boolean) this.getIntent().getExtras().get(FIRST_RUN);

        if (first_run)
        {
            pre = false;
        }
        else
        {
            current_page = (Integer) this.getIntent().getExtras().get(CURRENT_PAGE);
            page_count = (Integer) this.getIntent().getExtras().get(PAGE_COUNT);

            if (current_page.equals(page_count))
            {
                next = false;
            }
            else if (current_page == 1)
            {
                pre = false;
            }

        }

        gender = (String) this.getIntent().getExtras().get(GENDER);
        alphabet = (String) this.getIntent().getExtras().get(ALPHABET);


        setupFooterMenu(listView, next, pre);
        showDialog(PROGRESS);
        serviceThread.start();
    }

    private void setupFooterMenu(ListView listView, Boolean disableNext, Boolean disablePre)
    {
        LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        menu = vi.inflate(R.layout.menu, null);


        statusBox = (TextView) menu.findViewById(R.id.statusbox);

        preImage = (ImageButton) menu.findViewById(R.id.pre);


        preImage.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View view)
            {
                handlePrevious();
            }
        });


        nextImage = (ImageButton) menu.findViewById(R.id.next);
        nextImage.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View view)
            {
                handleNext();
            }
        });

        preImage.setEnabled(disablePre);
        nextImage.setEnabled(disableNext);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.list_menu, menu);

        return true;   //To change body of overridden methods use File | Settings | File Templates.
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        int id = item.getItemId();
        switch (id)
        {
            case R.id.search:
                startActivity(new Intent(this, TabLaunched.class));
                return true;
        }
        return false;
    }

    private void handleNext()
    {


        current_page = current_page + 1;

        Intent i = new Intent(this, NameList.class);
        i.putExtra(GENDER, gender);
        i.putExtra(ALPHABET, alphabet);
        i.putExtra(FIRST_RUN, false);
        i.putExtra(CURRENT_PAGE, current_page);
        i.putExtra(PAGE_COUNT, page_count);

        startActivity(i);
         this.finish();

    }

    private void handlePrevious()
    {
        current_page = current_page - 1;

        Intent i = new Intent(this, NameList.class);
        i.putExtra(GENDER, gender);
        i.putExtra(ALPHABET, alphabet);
        i.putExtra(FIRST_RUN, false);
        i.putExtra(CURRENT_PAGE, current_page);

        startActivity(i);
        this.finish();


    }

    @Override
    protected Dialog onCreateDialog(int id)
    {
        ProgressDialog dialog = null;
        switch (id)
        {
            case PROGRESS:
                ProgressDialog progressDialog = new ProgressDialog(NameList.this);

                progressDialog.setTitle("Fetching");
                progressDialog.setMessage("Names");
                // progressDialog.setIndeterminate(true);
                dialog = progressDialog;
        }

        return dialog;

    }


    private List<Name> getNames() throws IOException, JSONException
    {
        List<Name> names = client.getNamesObject(alphabet, gender, current_page);
        return names;
    }

    private Integer getCount() throws IOException
    {
        Integer pageCount = client.count(alphabet, gender);
        return pageCount;
    }

    @Override
    public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo)
    {
        super.onCreateContextMenu(contextMenu, view, contextMenuInfo);    //To change body of overridden methods use File | Settings | File Templates.
        contextMenu.add(0, FAVORATES, 0, "Add To Favorite");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK && current_page > 1)
        {
            handlePrevious();
            return true;
        }
        else
        {
            startActivity(new Intent(this, TabLaunched.class));
            this.finish();
            return true;
        }


    }


    @Override
    public boolean onContextItemSelected(MenuItem menuItem)
    {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuItem.getMenuInfo();

        if (menuItem.getItemId() == FAVORATES)
        {
            final Name currrntName = names.get(info.position);
            addFavorate(currrntName);
            return true;
        }
        else
        {

            return super.onContextItemSelected(menuItem);    //To change body of overridden methods use File | Settings | File Templates.
        }
    }


    private void addFavorate(Name name)
    {
        NamesDao dao = new NamesDao(this);
        dao.storeFavorate(name);
        dao.cleanup();
    }

    private class ServiceThread extends Thread
    {
        @Override
        public void run()
        {
            super.run();    //To change body of overridden methods use File | Settings | File Templates.
            try
            {
                if (first_run)
                {
                    page_count = getCount();
                    preImage.setEnabled(false);

                    if (page_count == 1)
                    {
                        nextImage.setEnabled(false);
                        current_page = 1;
                    }
                    if (page_count > 1)
                    {
                        getListView().addFooterView(menu);
                        current_page = 1;
                    }
                }
                else
                {
                    getListView().addFooterView(menu);
                }
                names = getNames();
                handler.sendEmptyMessage(0);
            }
            catch (Exception e)
            {
                dismissDialog(PROGRESS);

            }

        }
    }

}
